# -*- coding: utf-8 -*-

import random


def random_by_weight(random_item, weights, begin=0, end=None):
    # type: (list, list, int, int) -> vars
    """
    使用权值法，根据权值返回一个列表中的元素
    :param random_item: 随机池
    :param weights: 权重，应与随机池对应
    :param begin: 起始位置
    :param end: 结束位置
    :return: 根据权值随机出的元素
    """
    weight_sum = 0
    if not end:
        end = len(weights)
    for _ in xrange(begin, end):
        weight_sum += weights[_]
    rand = random.randint(0, weight_sum - 1)
    for _ in xrange(end - begin):
        rand -= weights[_]
        if rand < 0:
            return random_item[_]
    pass

